<template>
  <div>
    <div>
      <component :is="currentHeader"
                 :total="totalCount"
                 :unreadCount="unreadCount"
                 :selectInputTo="selectInput"
                 :logicDeleteMethod="handleLogicDelete"
                 :deleteMethod="handleDelete"
                 :allReadMethod="handleAllRead"
                 :readMethod="handleRead"
                 :unreadMethod="handleunRead"
                 :starMethod="handleStar"
                 :unstarMethod="handleUnStar"
                 :moveMethod2="handleMove2"
                 :moveMethod3="handleMove3"
      ></component>
    </div>

    <div class="mailbox-list">

    <el-table
        ref="multipleTable"
        :data="emailList"
        :cell-style="{'text-align':'center'}"
        :header-cell-style="{'text-align':'center'}"
        tooltip-effect="dark"
        v-model="multipleSelection"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="emailId"
          label="邮件id"
          width="100"
      ></el-table-column>
      <el-table-column
          label="是否已读"
          width="100"
      >
        <template slot-scope="scope">
          <!--          {{ scope.row.isstarred }}-->
            <i v-if="scope.row.isread === 1" class="iconfont icon-MESSAGEREAD"></i>
            <i v-else class="iconfont icon-IMPORTANTEMAIL"></i>
        </template>
      </el-table-column>
      <el-table-column
          prop="subject"
          label="主题"
          width="180"
      >
        <template slot-scope="scope">
           <span @click="handleCellClick(scope.row)">
          {{scope.row.subject}}
           </span>
        </template>
      </el-table-column>
      <el-table-column
          prop="fromMail"
          label="发件人"
          width="240"
      ><template slot-scope="scope">
        <span style="margin-left: 10px">
           <span @click="handleCellClick(scope.row)">
          {{ scope.row.fromMail}}
           </span>
        </span>
      </template></el-table-column>
      <el-table-column
          prop="toMail"
          label="收件人"
          width="240"
      >
        <template slot-scope="scope">
           <span @click="handleCellClick(scope.row)">
          {{scope.row.toMail}}
           </span>
        </template>
      </el-table-column>
      <el-table-column
          prop="sendtime"
          label="日期"
          width="180"
      >
      </el-table-column>
      <el-table-column
          label="星标收藏"

      >
        <template slot-scope="scope">
<!--          {{ scope.row.isstarred }}-->
          <el-button type="text" @click="handleStarred(scope.row)">
          <el-icon
              v-if="scope.row.isstarred === 1"
              class="is-starred"
              name="star-on"

          ></el-icon>
          <el-icon
              v-else
              class="is-not-starred"
              name="star-off"
          ></el-icon>
<!--            <el-icon :name="starIconName" @click="handleStarred(scope.row)"></el-icon>-->
          </el-button>
        </template>
      </el-table-column>
      <!-- 其他你需要的列 -->
<!--      <el-table-draggable-->
<!--          v-model="emailList"-->
<!--          @dragstart="handleDragStart"-->
<!--          @dragend="handleDragEnd"-->
<!--          tag="tbody"-->
<!--      ></el-table-draggable>-->
    </el-table>

    <!-- Element UI分页器 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalEmails"
    ></el-pagination>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import {mapGetters, mapState, mapActions, mapMutations} from "vuex";
import DraftHeader from "@/components/Header/DraftHeader.vue";
import InboxHeader from "@/components/Header/InboxHeader.vue";
import SentHeader from "@/components/Header/SentHeader.vue";
import SpamHeader from "@/components/Header/SpamHeader.vue";
import DeletedHeader from "@/components/Header/DeletedHeader.vue";
import StarHeader from "@/components/Header/StarHeader.vue";
import SearchHeader from "@/components/Header/SearchHeader.vue";


export default {
  name:'MailboxList',
  inject: ['reload'],
  props:['folderId'],
  data() {
    return {
      multipleSelection: [],
      emailList: [], // 邮件列表
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      totalEmails: 0, // 总邮件数
      unreadEmails: 0, // 总邮件数
      emailId:null,
      drag: false,
      hoveredFolderId: null, // 用于存储鼠标悬停的文件夹ID
      isstarred: 0,
      isread:0,
    };
  },
  components: {
    InboxHeader,
    DraftHeader,
    SentHeader,
    DeletedHeader,
    SpamHeader,
    StarHeader,
    SearchHeader,

  },
  computed: {
    ...mapGetters(['folderTo','selectInputTo']),
    ...mapState(['emailList', 'folders','user']),
    currentHeader() {
      switch (this.folderTo) {
        case 1:
          return 'DraftHeader';
        case 2:
          return 'InboxHeader';
        case 3:
          return 'SentHeader';
        case 4:
          return 'DeletedHeader';
        case 5:
          return 'SpamHeader';
        case 6:
          return 'StarHeader';
        case 7:
          return 'SearchHeader';

          // ... 其他case
        default:
          return null; // 或默认标签头
      }

    },
    unreadCount() {
      return this.unreadEmails;
    },

    totalCount(){
      return this.totalEmails;
    },
    selectInput() {
      return this.selectInputTo;
    },
  },
    created() {
      //异步创建一个异步任务，当folderId不为空时，执行getEmailList()
      console.log("floderTo " + this.folderTo)
      console.log("页面创建SelectInput"+this.selectInputTo)
      console.log("未读"+this.unreadCount);
      // this.folderId = this.folderTo;
      this.getEmailList();
      this.unreadEmailsCount();

    },
    methods: {
      ...mapActions(['moveEmail','replaceComponent']),
      ...mapMutations(['setEmailList']),
      async getEmailList() {
        console.log("emailfolderTo" + this.folderTo);
        if(this.folderTo===7&&this.selectInputTo!==""){
          console.log("eselectInput"+this.selectInputTo+' 当前用户'+this.user.userId)
          await  axios.get('http://localhost:8989/email/search', {
            params: {
              userId: this.user.userId,
              keyword: this.selectInputTo,
              pageNum: this.currentPage,
              pageSize: this.pageSize,
            },
          })
              .then((response) => {
                console.log(response.data.records);
                this.emailList = response.data.records;
                this.totalEmails = response.data.total;
                this.$store.commit('setEmailList', this.emailList);
                console.log("totalEmails" + this.totalEmails);
              });

        } else if (this.folderTo === 6){
          await  axios.get('http://localhost:8989/email/star_list', {
            params: {
              userId: this.user.userId,
              pageNum: this.currentPage,
              pageSize: this.pageSize,
            },
          })
              .then((response) => {

                console.log(response.data.records);
                this.emailList = response.data.records;
                this.totalEmails = response.data.total;
                this.$store.commit('setEmailList', this.emailList);
                console.log("totalEmails" + this.totalEmails);

              })
              .catch((error) => {
                console.error(error);
              });
        }else {
          await  axios.get('http://localhost:8989/email/list', {
            params: {
              folderId: this.folderTo,
              userId: this.user.userId,
              pageNum: this.currentPage,
              pageSize: this.pageSize,
            },
          })
              .then((response) => {
                console.log(response.data.records);
                this.emailList = response.data.records;
                this.totalEmails = response.data.total;
                this.$store.commit('setEmailList', this.emailList);
                console.log("totalEmails" + this.totalEmails);

              })
              .catch((error) => {
                console.error(error);
              });

        }

      },
      async unreadEmailsCount() {
        console.log("unreadthis.folderTo"+this.folderTo)
        if(this.folderTo===6){
          await  axios.get('http://localhost:8989/email/starUnReadCount?userId='+this.user.userId)
              .then((response) => {
                this.unreadEmails =  response.data;
              })
              .catch((error) => {
                console.error(error);
              });
        }else {
          await  axios.get('http://localhost:8989/email/unreadCount?folderId='+this.folderTo+"&userId="+this.user.userId)
              .then((response) => {
                console.log("未读数： "+response.data);
                this.unreadEmails =  response.data;
              })
              .catch((error) => {
                console.error(error);
              });

        }
      },
      handleCellClick(row) {
        this.lastClickedRow = row; // 更新最近一次点击的行数据
        console.log("行id"+row.emailId);
        this.$store.commit('setEmailId', row.emailId);
        // this.$emit('switch');
        this.Read(row.emailId);

        if (this.folderTo===1){
          if(row.emailId!==null){
            const componentName = 'DraftDetail';
            this.replaceComponent(componentName);
          }
          this.$router.push({ name: 'DraftDetail', params: { id: row.emailId } });

        }else{
          if(row.emailId!==null){
            const componentName = 'MailDetail';
            this.replaceComponent(componentName);
          }

          this.$router.push({ name: 'MailDetail', params: { id: row.emailId } });
        }

      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.getEmailList();
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getEmailList();
      },
      handleRead() {
        // 删除选中的邮件
        const emailIds = this.multipleSelection.map(row => row.emailId);
        for (let i = 0; i < emailIds.length; i++) {
          const emailid = emailIds[i];
          console.log("              "+emailid);
          this.Read(emailid);
        }
        this.multipleSelection = [];
        // this.reload();

      },
      handleunRead() {
        // 删除选中的邮件
        const emailIds = this.multipleSelection.map(row => row.emailId);
        for (let i = 0; i < emailIds.length; i++) {
          const emailid = emailIds[i];
          console.log("              "+emailid);
          this.unRead(emailid);
        }

        this.multipleSelection = [];


      },
      handleUnStar(){
        const emailIds = this.multipleSelection.map(row => row.emailId);
        for (let i = 0; i < emailIds.length; i++) {
          const emailid = emailIds[i];
          console.log("    UnStar    "+emailid);
          this.unStarred(emailid);
        }
        this.multipleSelection = [];
        this.reload();
      },
      handleStar(){
        const emailIds = this.multipleSelection.map(row => row.emailId);
        for (let i = 0; i < emailIds.length; i++) {
          const emailid = emailIds[i];
          console.log("              "+emailid);
          this.Starred(emailid);
        }
        this.multipleSelection = [];
        this.reload();

      },
      handleLogicDelete() {
        // 删除选中的邮件
        const emailIds = this.multipleSelection.map(row => row.emailId);
        for (let i = 0; i < emailIds.length; i++) {
          const emailid = emailIds[i];
          console.log("     logicdelete     "+emailid);
          this.logicDelete(emailid);
        }
        this.multipleSelection = [];
      },
      async logicDelete(emailid) {
        console.log("ids " + emailid);
        await axios.post('http://localhost:8989/email/logic_delete?emailId=' + emailid);
        this.getEmailList();
        this.unreadEmailsCount();
      },
      handleDelete() {
        // 删除选中的邮件
        const emailIds = this.multipleSelection.map(row => row.emailId);
        for (let i = 0; i < emailIds.length; i++) {
          const emailid = emailIds[i];
          this.Delete(emailid);
        }
        this.multipleSelection = [];
        this.reload();
      },
      async Delete(emailid) {
        console.log("ids " + emailid);
        await axios.post('http://localhost:8989/email/delete?emailId=' + emailid);
        this.getEmailList();
        this.unreadEmailsCount();
      },
      handleFolderHover(folderId) {
        if (this.drag) {
          this.hoveredFolderId = folderId;
        }
      },
      handleStarred(email) {
        // 切换邮件的星标状态
        console.log("email.isstarred " + email.isstarred);

        if (email.isstarred===1) {
          console.log("ID1"+email.emailId)
          // 如果邮件已星标，则取消星标
          this.unStarred(email.emailId);
          email.isstarred=0;
          this.reload;
        }else if(email.isstarred===0){
          console.log("ID0 "+email.emailId)
          this.Starred(email.emailId);
          email.isstarred=1;
          this.reload;

        }
      },
     unStarred(emailid){
        console.log("unstarred "+emailid);
       axios.post('http://localhost:8989/email/unstar?emailId='+emailid)
            .then((response) => {
              console.log(response.data);
              this.getEmailList();
            })
            .catch((error) => {
              console.error(error);
            });

      },
       Starred(emailid){
         console.log("starred "+emailid);
         axios.post('http://localhost:8989/email/star?emailId='+emailid)
            .then((response) => {
              console.log(response.data);
              this.getEmailList();
            })
            .catch((error) => {
              console.error(error);
            });

      },
      unRead(emailid){
        axios.post('http://localhost:8989/email/unread?emailId='+emailid)
            .then((response) => {
              console.log(response.data);
              // this.getEmailList();
              // this.unreadEmailsCount();
              this.reload();

            })
            .catch((error) => {
              console.error(error);
            });

      },
      Read(emailid){
        console.log("read " + emailid);
        axios.post('http://localhost:8989/email/read?emailId='+emailid)
            .then((response) => {
              console.log(response.data);
              // this.isread=1;
              // this.getEmailList();
              // this.unreadEmailsCount();
              this.reload();
            })
            .catch((error) => {
              console.error(error);
            });
      },
      handleMove2(){
        const emailIds = this.multipleSelection.map(row => row.emailId);
        for (let i = 0; i < emailIds.length; i++) {
          const emailid = emailIds[i];
          this.Move(emailid,2);
          this.reload;
        }
        this.multipleSelection = [];
      },
      handleMove3(){
        const emailIds = this.multipleSelection.map(row => row.emailId);
        for (let i = 0; i < emailIds.length; i++) {
          const emailid = emailIds[i];
          this.Move(emailid,3);
          this.reload;
        }
        this.multipleSelection = [];
      },
      Move(emailid, newFolderId) {
        console.log("email.folderId " + this.folderId);
        axios.post('http://localhost:8989/email/move?emailId='+emailid+'&folderId='+newFolderId)
            .then((response) => {
              console.log(response.data);
              this.getEmailList();
              this.unreadEmailsCount();
              this.reload;
            })
            .catch((error) => {
              console.error(error);
            });

      },
      handleAllRead(){
        console.log("allread "+this.folderTo);
        if(this.folderTo===6){
          axios.post('http://localhost:8989/email/allStarRead')
              .then((response) => {
                console.log(response.data);
                this.getEmailList();
                this.unreadEmailsCount();
                this.reload();
              })
              .catch((error) => {
                console.error(error);
              });
        }else{
          axios.post('http://localhost:8989/email/allRead?folderId='+this.folderTo)
              .then((response) => {
                console.log(response.data);
                this.getEmailList();
                this.unreadEmailsCount();
                this.reload();
              })
              .catch((error) => {
                console.error(error);
              });
        }
      },
    },
    watch: {
      // 监听drag状态，以在拖动时禁用其他操作（可选）
      folderTo(newVal, oldVal) {
        console.log("watch folderTo: " + newVal);
        // 注意：通常不需要重新赋值，因为 newVal 已经是新的值
        // this.folderTo = newVal; // 这一行通常是不需要的
        this.getEmailList();
        this.reload();
      },
      selectInputTo(newVal, oldVal) {
        console.log("watch selectInput: " + newVal);
        // 注意：通常不需要重新赋值，因为 newVal 已经是新的值
        // this.folderTo = newVal; // 这一行通常是不需要的
        this.getEmailList();
        this.reload();
      },
      unreadCount(newVal, oldVal) {
        this.unreadEmailsCount();
      },
      totalCount(newVal, oldVal) {
        this.getEmailList();
      },
      emailId(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.getEmailList();
        }
      },



    },
};
</script>
<style >
@import '~@/assets/icon/iconfont.css';
.mailbox-list{

}
.is-starred {
  color: #fce55f; /* 已星标颜色 */
  font-size: 25px;
}
.is-not-starred {
  color: #ccc; /* 未星标颜色 */
  font-size: 25px;
}
.is-read{
  color: #ccc;/* 已读邮件图标样式 */
  font-size: 25px;
}
.is-unread{
  color: #bb1111;/* 未读邮件图标样式 */
  font-size: 25px;
}
.last-clicked-marker {
  color: #409EFF; /* 图标颜色，可以根据需要调整 */
  margin-right: 8px; /* 图标和文本之间的间距 */
}
.icon-IMPORTANTEMAIL{
  font-size: 25px;
  color: #9a6e3a;
}
.icon-MESSAGEREAD{
  font-size: 25px;
  color: #afaeae;
}

</style>